/**
 * Created by macos on 14/11/11.
 */

var bcrypt = require('bcrypt');
var crypto = require('crypto');

module.exports = {

  types:{
    description:function(value) {
      return true;
    }
  },

  attributes: {
    serviceName: {
      type: 'string',
      required: true,
      description: '消息服务的名称'
    },
    userId: {
      type: 'string',
      required: false,
      description: '授权用户的id'
    },
    grantType: {
      type: 'string',
      required: true,
      enum: ['password','code'],
      description: '获取令牌的类型'
    },
    tokenType: {
      type: 'string',
      required: true,
      defaultsTo:"bearer",
      description: 'token类型'
    },
    scope: {
      type: 'string',
      required: false
    },
    refreshToken: {
      type: 'string',
      required: true,
      description: '刷新令牌'
    }
  },

  beforeValidate:function(values,next) {
      values.refreshToken = crypto.randomBytes(64).toString('hex');
      next();
  },

  beforeCreate: function (values, next) {
      //根据用户名、密码校验获取令牌
      MessageService.findOne({name:values.serviceName})
          .exec(function(err, result){
              if (err) {
                  sails.log.error(err);
                  return next(err);
              }

              if (_.has(result, 'id')) {
                  if(!values.authorization){
                      err = new Error();
                      err.message = 'authorization not find!';
                      err.status = 404;
                      return next(err);
                  }
                  if(!values.timestamp){
                      err = new Error();
                      err.message = 'timestamp not find!';
                      err.status = 404;
                      return next(err);
                  }
                  var authArray = [];
                  authArray.push(values.serviceName);
                  authArray.push(result.secret);
                  authArray.push(values.timestamp);
                  authArray.sort();
                  var authorization = authArray[0]+authArray[1]+authArray[2];

                  var check = bcrypt.compareSync(authorization, values.authorization);

                  if (check) { //校验成功，生成token
                      delete values.authorization;
                      delete values.timestamp;

                      next();
                  }  else {
                      err = new Error();
                      err.message = 'authorization is error';
                      err.status = 403;
                      return next(err);
                  }

              } else {

                  err = new Error();
                  err.message = '\''+ values.serviceName + '\' is not exist!';
                  err.status = 404;

                  return next(err);
              }

          });
  },

  beforeUpdate:function (values, next) {

  }
}